﻿using B.S.DataBase.MyProject.Domain.Management;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.Management;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.Management
{
    public class GetBasicFollowCommandHandler : IRequestHandler<GetBasicFollowCommand, APIResult<ApiPaging<Basic>>>
    {
        private readonly SqlSugarContext sqlSugar;

        public GetBasicFollowCommandHandler(SqlSugarContext sqlSugar)
        {
            this.sqlSugar = sqlSugar;
        }
        public Task<APIResult<ApiPaging<Basic>>> Handle(GetBasicFollowCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<ApiPaging<Basic>> result = new APIResult<ApiPaging<Basic>>();
                var entity = sqlSugar.db.Queryable<Basic>().Where(x => x.Status != "未随访");
                if (!string.IsNullOrEmpty(request.Name))
                {
                    entity = entity.Where(x => x.Name.Contains(request.Name));
                }
                if (!string.IsNullOrEmpty(request.FollowUpPlan))
                {
                    entity = entity.Where(x => x.FollowUpPlan == (request.FollowUpPlan));
                }
                if (request.ScheduledFollowUpTime != null)
                {
                    entity = entity.Where(x => x.ScheduledFollowUpTime == (request.ScheduledFollowUpTime));
                }
                entity = entity.OrderByDescending(x => x.BasicId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                ApiPaging<Basic> paging = new ApiPaging<Basic>();
                paging.TotalCount = entity.Count();
                paging.TotalPage = (int)Math.Ceiling(paging.TotalCount * 1.0 / request.PageSize);
                result.Code = APIEnum.查询成功;
                result.Msg = APIEnum.查询成功.ToString();
                result.data = paging;
                result.data.list = entity.ToList();
                return Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
